﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Text.RegularExpressions;

namespace CooWork.Services
{
    public class CommonHelper
    {
        public static string ClassToAnonymous(object c)
        {
            Type t = c.GetType();
            string ret = "{";
            foreach (FieldInfo field in t.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
            {
                if (field.FieldType.Equals(typeof(String)) || field.FieldType.IsValueType)
                {
                    string vname = Regex.Replace(field.Name, @"^.*<|>.+$", "", RegexOptions.IgnoreCase);
                    string s1 = field.GetValue(c) == null ? "" : field.GetValue(c).ToString();
                    if (Regex.IsMatch(s1, @"^(-?\d+)(\.\d+)?$"))
                    {
                        ret += @"'" + vname + @"':" + s1 + ",";
                    }
                    else
                    {
                        ret += @"'" + vname + @"':'" + s1 + @"',";
                    }
                    
                }
            }
            ret = ret.Trim(',');
            ret += " }";           


            return ret;

        }


    }
}